#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string>

#include "net_tools.h"

const int LISTEN_PORT  = 6666;
const int LISTEN_COUNT = 5;

using namespace std;

int main()
{
    struct sockaddr_in addr; 

    int fd = socket(AF_INET, SOCK_STREAM, 0);
    assert(fd >= 0);

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port   = htons(LISTEN_PORT);

    int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    assert(ret == 0);

    ret = listen(fd, LISTEN_COUNT);
    assert(ret == 0);

    while (1) {

        struct sockaddr_in caddr;
        
        int len = sizeof(caddr);

        int cfd = accept(fd, (struct sockaddr*)&caddr, (socklen_t*)&len);
        assert(cfd >= 0);
        printf("new connection comming, fd:%d\n", cfd);

        while (1) {
/*
            string content;
            int ret = NetTools::recv_packet(cfd, content);
            if (ret > 0) {
                printf("server socket recv, fd:%d, content:%s\n", cfd, content.c_str());
            } else if (ret == 0) {
                printf("server socket recv close, fd:%d\n", cfd);
                close(cfd);
                break ;
            } else {
                printf("server socket recv error, fd:%d, errno:%d\n", cfd, errno);
            }

            usleep(200 * 1000);

            ret = NetTools::send_packet(cfd, content);
            if (ret > 0) {
                printf("server socket send, fd:%d, content:%s\n", cfd, content.c_str());
            } else if (ret == 0) {
                printf("server socket send close, fd:%d\n", cfd);
                close(cfd);
                break ;
            } else {
                printf("server socket send error, fd:%d, errno:%d\n", cfd, errno);
            }
*/
        }
    }

    return 0;
}

